package org.springcloud.plugin.framework.loadbalance.weight;

import com.netflix.loadbalancer.Server;
import org.springcloud.plugin.common.entity.DiscoveryEntity;
import org.springcloud.plugin.common.entity.RuleEntity;
import org.springcloud.plugin.common.entity.WeightEntityWrapper;
import org.springcloud.plugin.common.entity.WeightFilterEntity;
import org.springcloud.plugin.framework.adapter.CoreAdapter;

/**
 * @Author yanggld
 * @Date 2019/12/17-18:29
 * @Description
 */
public class RuleWeightRandomLoadBalanceAdapter extends AbstractWeightRandomLoadBalanceAdapter {

	public RuleWeightRandomLoadBalanceAdapter(CoreAdapter coreAdapter) {
		super(coreAdapter);
	}

	@Override
	public WeightFilterEntity getT() {
		RuleEntity ruleEntity = coreAdapter.getRule();
		if (ruleEntity == null) {
			return null;
		}
		DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity();
		if (discoveryEntity == null) {
			return null;
		}
		WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity();
		return weightFilterEntity;
	}

	@Override
	public int getWeight(Server server, WeightFilterEntity weightFilterEntity) {
		String providerServiceId = coreAdapter.getServerServiceId(server);
		String providerVersion = coreAdapter.getServerVersion(server);
		String providerRegion = coreAdapter.getServerRegion(server);
		String serviceId = coreAdapter.getServiceId();

		return WeightEntityWrapper.getWeight(weightFilterEntity, providerServiceId, providerVersion, providerRegion, serviceId);

	}
}
